#include "StdAfx.h"
#include "GroupsDb.h"
#ifdef WIN32_PLATFORM_PSPC
#include "resourceppc.h"
#else
#include "resourcesp.h"
#endif

const TCHAR *CGroupsDb::DB_NAME = _T("Groups");

CGroupsDb::CGroupsDb(void)
    : CDbBase(DB_NAME, sizeof(Record))
    , m_MaxId(0)
{
}

CGroupsDb::~CGroupsDb(void)
{
}

DWORD CGroupsDb::Open(void)
{
    DWORD Err = CDbBase::Open();
    if (Err != ERROR_SUCCESS)
        return Err;

    UINT Count = GetCount();
    if (Count == UINT_MAX)
        return ERROR_GEN_FAILURE;

    if (Count == 0)
    {
        CString GroupName;
        GroupName.LoadString(IDS_REC_0_GROUP_NAME);

        UINT AssignedId = 0;
        Add(GroupName, &AssignedId);
        ASSERT(AssignedId == CDbBase::FIRST_RECORD_ID);
        UNREFERENCED_PARAMETER(AssignedId);
    }
    else
    {
        Record r = {0};
        Err = m_DbMgr.ReadRecord(Count - 1, (BYTE *)&r, sizeof(Record), NULL);
        if (Err != ERROR_SUCCESS)
            return Err;

        m_MaxId = r.Id;     // Read can fail if empty
    }

    return ERROR_SUCCESS;
}

DWORD CGroupsDb::Add(CString GroupName, UINT *pAssignedId)
{
    Record r = {0};
    HRESULT hr = StringCchCopy(
        r.GroupName,
        sizeof(r.GroupName) / sizeof(TCHAR),
        GroupName);
    if (FAILED(hr))
        return ERROR_INSUFFICIENT_BUFFER;

    r.Id = m_MaxId + 1;

    UINT Count = GetCount();
    if (Count == UINT_MAX)
        return ERROR_GEN_FAILURE;

    DWORD Err = m_DbMgr.WriteRecord(Count, (BYTE *)&r, sizeof(Record));
    if (Err != ERROR_SUCCESS)
        return Err;

    m_MaxId++;

    if (pAssignedId)
        *pAssignedId = r.Id;

    return ERROR_SUCCESS;
}

DWORD CGroupsDb::Get(UINT Index, UINT *pId, CString *pGroupName)
{
    Record r = {0};
    DWORD Err = m_DbMgr.ReadRecord(Index, (BYTE *)&r, sizeof(Record), NULL);
    if (Err != ERROR_SUCCESS)
        return Err;

    if (pId)
        *pId = r.Id;
    if (pGroupName)
        *pGroupName = r.GroupName;

    return ERROR_SUCCESS;
}

DWORD CGroupsDb::GetFromId(UINT Id, CString *pGroupName, UINT *pIndex)
{
    UINT i = 0;
    Record r = {0};
    DWORD Err = m_DbMgr.ReadRecord(i, (BYTE *)&r, sizeof(Record), NULL);
    while (Err == ERROR_SUCCESS)
    {
        if (Id == r.Id)
        {
            if (pGroupName)
                *pGroupName = r.GroupName;
            if (pIndex)
                *pIndex = i;

            return ERROR_SUCCESS;
        }

        i++;
        Err = m_DbMgr.ReadRecord(i, (BYTE *)&r, sizeof(Record), NULL);
    }

    return ERROR_NOT_FOUND;
}
